#include <stdio.h>
#include "lcd.h"
#include "i2c.h"

#define I2C_ADDR    0x54

static int i2c_write_byte(uint8_t reg, uint8_t data)
{
    i2c_t *i2c;

    i2c = i2c_new();

    /* Open the i2c-1 bus */
    if (i2c_open(i2c, "/dev/i2c-1") < 0) {
        fprintf(stderr, "i2c_open(): %s\n", i2c_errmsg(i2c));
        i2c_free(i2c);
        return -1;
    }

    uint8_t msg_addr[2] = { reg, data };
    struct i2c_msg msgs[1] =
        {
            { .addr = I2C_ADDR, .flags = 0, .len = 2, .buf = msg_addr },
        };

    /* Transfer a transaction with two I2C messages */
    if (i2c_transfer(i2c, msgs, 1) < 0) {
        fprintf(stderr, "i2c_transfer(): %s\n", i2c_errmsg(i2c));
        i2c_close(i2c);
        i2c_free(i2c);
        return -1;
    }

    i2c_close(i2c);
    i2c_free(i2c);

    return 0;
}

int lcd_brightness_set(int brightness)
{
    unsigned char value;
    switch (brightness)
    {
    case 0:
        value = 0xC8;
        break;
    case 1:
        value = 0x96;
        break;
    case 2:
        value = 0x64;
        break;
    case 3:
        value = 0x32;
        break;
    default:
        value = 0x64;
        break;
    }
    return i2c_write_byte(0xCE, value);
}

int lcd_display_onoff(int onoff)
{
    int ret;
    if (onoff) {
        ret = i2c_write_byte(0x94, 0xDA);
    } else {
        ret = i2c_write_byte(0x94, 0xD8);
    }
    return ret;
}